﻿using HuaCheng.DataAccess;
using HuaCheng.Model;
using HuaCheng.Views;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Windows.Forms;

namespace HuaCheng.Controller
{
    public class IndexPageControl
    {
        #region 设备列表树形图
        /// <summary>
        /// 从数据库设备表中查询设备节点添加到树形图
        /// </summary>
        /// <param name="allDev"></param>
        /// <param name="tnode"></param>
        /// <returns></returns>
        public static Dictionary<string, bool> AddDevicesToRoot(Dictionary<string, bool> allDev, TreeNode tnode)
        {
            List<Device> devices = DeviceHelper.GetTreeNodeList();
            TreeNode rootNode = new TreeNode();//根节点
            rootNode = tnode;
            rootNode.ImageIndex = 0;//普通节点图片
            foreach (Device dev in devices)
            {
                string cabinet = "cabnet" + dev.GID;//柜节点名称
                string mac = "device" + dev.MID;//中位机节点名称
                string key = dev.DevMac;//唯一标识中位机
                TreeNode cabinetNode = null;//柜节点
                TreeNode devNode = new TreeNode();//中位机节点
                devNode.Name = mac;
                devNode.Text = dev.MID + "(" + dev.DevIP + ")";
                foreach (TreeNode tn in rootNode.Nodes)
                {
                    string cabName = IndexPageControl.GetDevName(tn);
                    if (cabName == dev.GID.ToString())//如果树形图已存在该柜则添加中位机节点
                    {
                        cabinetNode = tn;
                        cabinetNode.ImageIndex = 0;//普通节点图片
                        if (!dev.DevDelete && dev.DevIP != null)
                            cabinetNode.Nodes.Add(devNode);//追加节点
                        break;
                    }
                }
                //如果柜节点未添加则先添加该柜
                if (cabinetNode == null)
                {
                    cabinetNode = new TreeNode();
                    cabinetNode.Name = cabinet;
                    cabinetNode.Text = dev.GID.ToString();//柜号名称
                    cabinetNode.ImageIndex = 0;//普通节点图片
                    if (!dev.DevDelete&&dev.DevIP != null)//如果设备被删除则不显示到树形列表
                        cabinetNode.Nodes.Add(devNode);//追加节点
                    rootNode.Nodes.Add(cabinetNode);
                }
                if (allDev.ContainsKey(key))
                    devNode.ImageIndex = allDev[key] ? 2 : 1;//未连接图片
                else
                {
                    if (!dev.DevDelete&&dev.DevIP != null)
                    {
                        devNode.ImageIndex = 1;
                        allDev.Add(key, false);
                    }
                }
            }            
            return allDev;
        }
        /// <summary>
        /// 动态添加连接
        /// </summary>
        /// <param name="tnode"></param>
        /// <param name="ip"></param>
        /// <param name="devType"></param>
        public static void NewConnect(TreeNode tnode, string ip, bool connect)
        {
            Device dev = DeviceHelper.QueryDeviceByIP(ip);
            string cabinetName = "cabnet" + dev.GID;
            string devName = "device" + dev.MID;
            TreeNode rootNode = tnode;//根节点
            TreeNode cabinetNode = null;//设备类型节点
            TreeNode devNode = new TreeNode();//设备节点
            devNode.Name = devName;
            devNode.Text = dev.MID + "(" + dev.DevIP + ")";
            devNode.ImageIndex = connect ? 2 : 1;
            foreach (TreeNode tn in rootNode.Nodes)
            {
                string cabName = IndexPageControl.GetDevName(tn);
                if (cabName == dev.GID.ToString())//如果已存在该柜已在树形图上
                {
                    cabinetNode = tn;
                    cabinetNode.Nodes.Add(devNode);//追加节点
                    break;
                }
            }
            if (cabinetNode == null)//如果未添加该柜
            {
                cabinetNode = new TreeNode();
                cabinetNode.Name = cabinetName;
                cabinetNode.Text = dev.GID.ToString();
                cabinetNode.Nodes.Add(devNode);//追加中位机节点
                rootNode.Nodes.Add(cabinetNode);
            }
        }
        /// <summary>  
        /// 获取当前使用的IP  
        /// </summary>  
        /// <returns></returns>  
        public static string GetClientLocalIPv4Address()
        {
            string strLocalIP = string.Empty;
            try
            {
                IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
                for (int i = 0; i < ipHost.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (ipHost.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        return ipHost.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                return "unknown";
            }
        }
        /// <summary>
        /// 获取当前没有正在运行所有通道的realid
        /// </summary>
        /// <param name="chlList"></param>
        /// <returns></returns>
        public static List<int> GetNoRunningChannel(List<Channel> chlList)
        {
            List<int> noRunningChlList = new List<int>();
            //初始化所有通道运行状态字典
            Dictionary<int, bool> chlRunStateDic = new Dictionary<int, bool>();
            for (int i = 0; i < chlList.Count; i++)
            {
                chlRunStateDic.Add(i, false);
            }
            for (int i = 0; i < chlList.Count; i++)
            {
                if (chlList[i].RunStat)//如果通道正在运行不能选择为整柜启动对象
                {
                    //获取与该通道并联的所有通道号,并联Id是主通道realId,所以这里以i为参数
                    List<int> allParaId = MutiChlHelper.GetChlById(i, chlList[i].DevIp, chlList[i].Gid, chlList[i].Mid);
                    if (allParaId.Count == 0)
                    {
                        chlRunStateDic[i] = true;
                    }
                    else//如果该运行通道存在并联通道，则并联通道也不能选择为整柜启动对象
                    {
                        for (int j = 0; j < allParaId.Count; j++)
                        {
                            chlRunStateDic[allParaId[j] - 1] = true;
                        }
                    }
                }
            }
            //将所有运行状态为false的通道号保存
            foreach (KeyValuePair<int, bool> item in chlRunStateDic)
            {
                if (item.Value == false)
                {
                    noRunningChlList.Add(item.Key);
                }
            }
            return noRunningChlList;
        }
        /// <summary>
        /// 新增设备
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="devtype"></param>
        public static void ModifyDevices(int gid, int mid, string ip)
        {
            DeviceHelper.ModifyDevices(gid, mid, ip);
        }
        //public static Dictionary<string, bool> AddDevicesToRoot(Dictionary<string, bool> allDev, TreeNode tnode)
        //{
        //    List<Device> devices = DeviceHelper.GetTreeNodeList();
        //    TreeNode rootNode = new TreeNode();//根节点
        //    rootNode = tnode;
        //    rootNode.ImageIndex = 0;//普通节点图片
        //    foreach (Device dev in devices)
        //    {
        //        string typeName = "devTyp" + dev.DevType;
        //        string devName = "device" + dev.DevIP;
        //        TreeNode devTypeNode = null;//设备类型节点
        //        TreeNode devNode = new TreeNode();//设备节点
        //        devNode.Name = devName;
        //        devNode.Text = dev.DevIP;
        //        string key = dev.DevIP + dev.DevType;
        //        if (allDev.ContainsKey(key))
        //            devNode.ImageIndex = allDev[key] ? 2 : 1;//未连接图片
        //        else
        //        {
        //            devNode.ImageIndex = 1;
        //            allDev.Add(key, false);
        //        }
        //        foreach (TreeNode tn in rootNode.Nodes)
        //        {
        //            string devTypeName = IndexPageControl.GetDevName(tn);
        //            if (devTypeName == dev.DevType)//如果已存在该设备类型
        //            {
        //                devTypeNode = tn;
        //                devTypeNode.ImageIndex = 0;//普通节点图片
        //                if (!dev.DevDelete)
        //                    devTypeNode.Nodes.Add(devNode);//追加节点
        //                break;
        //            }
        //        }
        //        if (devTypeNode == null)//如果未添加该设备类型
        //        {
        //            devTypeNode = new TreeNode();
        //            devTypeNode.Name = typeName;
        //            devTypeNode.Text = dev.DevType;//设备名称
        //            devTypeNode.ImageIndex = 0;//普通节点图片
        //            if (!dev.DevDelete)//如果设备被删除则不显示到树形列表
        //                devTypeNode.Nodes.Add(devNode);//追加节点
        //            rootNode.Nodes.Add(devTypeNode);
        //        }
        //    }
        //    return allDev;
        //}
        ///// <summary>
        ///// 动态添加连接
        ///// </summary>
        ///// <param name="tnode"></param>
        ///// <param name="ip"></param>
        ///// <param name="devType"></param>
        //public static void NewConnect(TreeNode tnode, string ip, string devType, bool connect)
        //{
        //    string typeName = "devTyp" + devType;
        //    string devName = "device" + ip;
        //    TreeNode rootNode = tnode;//根节点
        //    TreeNode devTypeNode = null;//设备类型节点
        //    TreeNode devNode = new TreeNode();//设备节点
        //    devNode.Name = devName;
        //    devNode.Text = ip;
        //    devNode.ImageIndex = connect ? 2 : 1;
        //    foreach (TreeNode tn in rootNode.Nodes)
        //    {
        //        string devTypeName = IndexPageControl.GetDevName(tn);
        //        if (devTypeName == devType)//如果已存在该设备类型
        //        {
        //            devTypeNode = tn;
        //            devTypeNode.Nodes.Add(devNode);//追加节点
        //            break;
        //        }
        //    }
        //    if (devTypeNode == null)//如果未添加该设备类型
        //    {
        //        devTypeNode = new TreeNode();
        //        devTypeNode.Name = "devTyp" + devType;
        //        devTypeNode.Text = devType;//设备名称
        //        devTypeNode.Nodes.Add(devNode);//追加节点
        //        rootNode.Nodes.Add(devTypeNode);
        //    }
        //}
        ///// <summary>
        ///// 新增设备
        ///// </summary>
        ///// <param name="ip"></param>
        ///// <param name="devtype"></param>
        //public static void ModifyDevices(int gid,int mid,string ip)
        //{
        //    DeviceHelper.ModifyDevices(gid,mid,ip);
        //}
        #endregion
        #region 并联模块
        /// <summary>
        /// 保存并联
        /// </summary>
        /// <param name="dev"></param>
        /// <param name="allId"></param>
        public static void SaveParallel(string dev,List<int> allId,int map,int mid,int gid)
        {
            List<MutiChl> muChls = new List<MutiChl>();
            DateTime dt = System.DateTime.Now;
            foreach (int chlId in allId)
            {
                MutiChl chl = new MutiChl()
                {
                    DevIp = dev,
                    Mid = mid,//中位机号
                    Gid = gid,
                    ChlId = chlId % map + 1,//映射id
                    ParallelId = allId[0],//并联id
                    InsertTime = dt
                };
                muChls.Add(chl);
            }
            MutiChlHelper.InsertParallel(muChls);//插入并联信息到数据库
        }
        /// <summary>
        /// 删除并联
        /// </summary>
        /// <param name="devId"></param>
        /// <param name="key"></param>
        public static void DeleteParallel(string devId,int gid,int mid,int key)
        {
            MutiChlHelper.DeleteParallel(devId,gid,mid,key);//删除并联表相应数据
        }
        #endregion
        #region 迁移模块
        /// <summary>
        /// 把迁移通道工步信息复制给目标通道并返回StepSetInfo对象
        /// </summary>
        public static StepSetInfo GetStepSetInfo(string ip,Channel sourceChl,Channel targetChl)
        {
            StepSetInfo sp = new StepSetInfo();
            List<StepInfo> currentList = new List<StepInfo>();
            Dictionary<int, Dictionary<string, string>> procDic = new Dictionary<int, Dictionary<string, string>>();
            Dictionary<int, Dictionary<string, string>> procSelDic = new Dictionary<int, Dictionary<string, string>>();
            try //从表中读取工步数据
            {
                List<byte[]> byteList = StepHelper.GetBinaryListById("0",ip, sourceChl.Gid,sourceChl.Mid, sourceChl.Cid);//查询待迁移通道工步信息
                if (byteList.Count > 0)
                {
                    List<StepInfo> loadStepList = new List<StepInfo>();
                    //将工步数据恢复成StepInfo对象
                    for (int i = 0; i < byteList.Count; i++)
                    {
                        //将字节数组反序列化StepInfo对象
                        StepInfo stepInfo = (StepInfo)SerializableControl.DeserializeWithBinary(byteList[i]);
                        loadStepList.Add(stepInfo);
                    }
                    //将工步list转为当前单位的数值
                    currentList = DataControl.DataConvertToCurrent(loadStepList);
                    //将保护条件转换为当前单位的数值
                    string testId = TestHelper.GetTestId(sourceChl.DevIp, sourceChl.Gid,sourceChl.Mid, sourceChl.Cid);//获取迁移测试id
                    sp.TestId = testId;
                    sp.StepList = currentList;
                    sp.Cid = targetChl.Cid;
                    sp.Mid = targetChl.Mid;
                    sp.Gid = targetChl.Gid;
                    sp.DevIp = ip;
                    sp.RealId = targetChl.RealId;
                    sp.StartStep = sourceChl.StepId;//起始工步
                    sp.isStandard = true;
                    List<int> chlList = MutiChlHelper.GetChlById(targetChl.RealId, ip, targetChl.Gid, targetChl.Mid);//并联号
                    sp.ParallelList = chlList;//并联通道号                
                    //把目标通道测试信息插入到测试表
                    if (chlList.Count > 1)
                    {
                        StepSet.SaveTestInfo(targetChl, currentList[0], testId,1);
                    }
                    else
                    {
                        StepSet.SaveTestInfo(targetChl, currentList[0], testId, 0);
                    }
                    //把工步信息保存到目标通道的工步信息
                    StepSet.SaveStepInfo(currentList,targetChl,testId);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message + e.StackTrace);
            }
            return sp;
        }
        #endregion
        #region 右键菜单日志模块
        /// <summary>
        /// 操作写入日志文件
        /// </summary>
        /// <param name="sender"></param>
        public static void WriteToLog(Object sender)
        {
            ToolStripMenuItem tsmi = sender as ToolStripMenuItem;
            string tsmiName = tsmi.Name;
            CheckLogControl.WriteToLocalLog(tsmiName);
        }
        #endregion
        #region 通用方法
        /// <summary>
        /// 根据设备通道名称获取实际id
        /// </summary>
        /// <param name="chlName"></param>
        /// <returns></returns>
        public static int GetRealIdByName(string chlName)
        {
            return Convert.ToInt32(chlName.Substring(6));
        }
        /// <summary>
        /// 获取设备IP或设备类型
        /// </summary>
        /// <param name="tnode"></param>
        /// <returns></returns>
        public static string GetDevName(TreeNode tnode)
        {
            return tnode.Name.Substring(6);//截取名称6位后的字符
        }
        #endregion
    }
}
